package com.ajun.controller;

import com.ajun.common.entity.R;
import com.ajun.entity.Payment;
import com.ajun.service.PaymentService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Payment Controller
 *
 * @author AJun
 * @date 2021-07-08
 */
@Slf4j
@RestController
@RequestMapping("/api/payment")
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Resource
    private EurekaDiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;

    @GetMapping("/discovery")
    public R<JSONObject> discovery() {
        List<String> services = discoveryClient.getServices();
        List<List<ServiceInstance>> instanceLists = new ArrayList<>();
        services.forEach(service -> {
            List<ServiceInstance> instances = discoveryClient.getInstances(service);
            instances.forEach(instance -> {
                System.out.println("instance id: " + instance.getInstanceId());
                System.out.println("instance host: " + instance.getHost());
                System.out.println("instance port: " + instance.getPort());
                System.out.println("instance scheme: " + instance.getScheme());
                System.out.println("instance service id: " + instance.getServiceId());
                System.out.println("instance service uri: " + instance.getUri());
                System.out.println("instance service metadata: " + instance.getMetadata());
                System.out.println("instance service isSecure: " + instance.isSecure());
            });
            instanceLists.add(instances);
        });

        JSONObject json = new JSONObject();
        json.put("port", serverPort);
        json.put("instanceLists", instanceLists);
        return R.ok(json);
    }

    @PostMapping("/create")
    public R<Boolean> createPayment(@RequestBody Payment payment) {
        log.info("负载均衡到: {}", serverPort);
        return paymentService.createPayment(payment);
    }

    @GetMapping("/get/{id}")
    public R<Payment> getPayment(@PathVariable("id") Long id) {
        log.info("负载均衡到: {}", serverPort);
        return paymentService.getPayment(id);
    }
}
